package cn.com.dcsgo.common.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * StringInIfNotNullValidator
 *
 * @author Dcsgo
 * @since 24/5/2025 上午 10:04
 */

public class StringInIfNotNullValidator implements ConstraintValidator<StringInIfNotNull, String> {

    private Set<String> allowedSet;

    @Override
    public void initialize(StringInIfNotNull constraintAnnotation) {
        allowedSet = new HashSet<>();
        allowedSet.addAll(Arrays.asList(constraintAnnotation.value()));
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 为空或者全是空白字符，不校验，视为通过
        if (!StringUtils.hasText(value)) {
            return true;
        }
        return allowedSet.contains(value);
    }
}
